import axios from 'axios'
import { Toast, Dialog } from 'vant';
import store from '@/store'
import router from '@/router'
import { getToken, removeToken } from '@/utils/auth'
const API_ROOT = '/';
// create an axios instance
const service = axios.create({
  baseURL: API_ROOT, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    //add app_id
    // if(store.state.app) {
    //   let app_id = store.state.app.id
    //   if(app_id)config.data = {app_id, ...config.data}
    //   if(config.method == 'get') {
    //     config.params = {app_id, ...config.data}
    //   }
    // }
    config.headers['Authorization'] = 'Bearer ' + getToken()
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.status !== 200) {
      Toast({
        message: res.status == 401?'登录失效，请重新登录':res.message || 'Error',
        onClose: data=> {
          if(res.status == 401) {
            removeToken()
            location.reload()
          }
        }
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res.data
    }
  },
  error => {
    // removeToken()
    // location.reload()
    console.log(error.response) // for debug

    Toast({
      message: error.response.status == 401?'登录失效，请重新登录':error.response.data.message || 'Error',
        onClose: data=> {
          if(error.response.status == 401) {
            removeToken()
            // router.push({ name: 'Index', query: {}})
            window.location.href = process.env.VUE_APP_PATH
            // location.reload()
          }
          if(error.response.status == 402) {
            router.push({ name: 'register'})
          }
        }
    });
    return Promise.reject(error)
  }
)

export default service
